#include "stdafx.h"
#include "ThreadpoolWait.h"

namespace Otl { namespace Win32
{

CThreadpoolWait::CThreadpoolWait(std::function<void()> callback)
	: m_wait{ ::CreateThreadpoolWait(CThreadpoolWait::WaitCallback, this, nullptr) },
	  m_callback{ std::move(callback) }
{
}

CThreadpoolWait::~CThreadpoolWait()
{
	if (m_wait != nullptr)
	{
		::CloseThreadpoolWait(m_wait);
	}
}

void CThreadpoolWait::Set(const CEvent & evt)
{
	::SetThreadpoolWait(m_wait, evt.Handle(), nullptr);
}

VOID CALLBACK CThreadpoolWait::WaitCallback(_Inout_ PTP_CALLBACK_INSTANCE instance,
                                            _Inout_ PVOID context,
                                            _Inout_ PTP_WAIT wait,
                                            _In_ TP_WAIT_RESULT waitResult)
{
	UNREFERENCED_PARAMETER(instance);
	UNREFERENCED_PARAMETER(wait);
	UNREFERENCED_PARAMETER(waitResult);

	auto this_ = reinterpret_cast<CThreadpoolWait *>(context);
	this_->m_callback();
}

}}